package com.huatai.exchange.deal;

import com.alibaba.fastjson.JSON;
import com.faneui.common.exception.BusinessException;
import com.faneui.common.utils.FileUtils;
import com.huatai.exchange.dal.model.ExcDataFileInfo;
import com.huatai.exchange.dal.model.ExcExchangeDateFile;
import com.huatai.exchange.facade.FileSourceContents;
import com.huatai.exchange.utils.FileDealUtils;
import com.huatai.exchange.utils.VelocityContextHelper;
import com.huatai.exchange.utils.VelocityUtils;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Service("fileCreateVelocityDealService")
public class FileCreateVelocityDealServiceImpl extends AbstractFileCreateDealServiceImpl implements FileCreateDealService {


    @Autowired
    private VelocityContextHelper velocityHelper;

    @Override
    public void downloadCreateFile(StringBuffer fileNames, StringBuffer filePaths, ExcExchangeDateFile exchangeDateFile, ExcDataFileInfo dataFileInfo, Map<String, Object> resvMap) throws BusinessException {
        String tmpFilePath = tmpFile + UUID.randomUUID().toString();
        try {
            File f = new File(tmpFilePath);
            Map<String, Object> excDataFileMap = JSON.parseObject(exchangeDateFile.getProperties(), HashMap.class);
            Map<String, Object> valueMap = JSON.parseObject(dataFileInfo.getValue(), HashMap.class);
            String fileName = FileDealUtils.formatStr(dataFileInfo.getFileName(), excDataFileMap, resvMap);
            String veloContent = FileDealUtils.formatStr((String) valueMap.get(FileSourceContents.VELOCITY_CONTENT), excDataFileMap, resvMap);
            Velocity.init();
            VelocityContext context = velocityHelper.fillContext(resvMap);
            String content = VelocityUtils.evaluate(context, veloContent);
            FileUtils.writeFile(f, content);
            // 文件中心  获取文件
            fileNames.append(",").append(fileName);
            String filePath = fileOperateService.uploadFile(f);
            filePaths.append(",").append(filePath);
        } catch (Exception ex) {
            BusinessException.throwBusinessException(ex);
        }
    }
}
